﻿using System;
using System.Globalization;
using System.Windows.Data;

namespace StockholmsStad.Windows.UI.Infrastructure.Converters
{
    [ValueConversion(typeof(bool?), typeof(string))]
    public class NullToBooleanConverter : IValueConverter
    {
        private const string NULL_STRING = "[[NullString]]";

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
            {
                return NULL_STRING;
            }

            bool parsedValue;
            if (bool.TryParse(value.ToString(), out parsedValue))
            {
                return parsedValue ? bool.TrueString : bool.FalseString;
            }
            
            return NULL_STRING;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
            {
                return null;
            }

            bool parsedValue;

            if (bool.TryParse(value.ToString(), out parsedValue))
            {
                return parsedValue;
            }

            return null;
        }
    }
}
